package nciae.db.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import nciae.db.pojo.entity.*;
import nciae.db.pojo.vo.*;
import nciae.db.common.CommonResult;
import nciae.db.mapper.*;
import nciae.db.service.ProjectService;
import nciae.db.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private ProjectMapper mapper;

    @Autowired
    private DocReportMapper docReportMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private DocSchemeMapper docSchemeMapper;

    @Autowired
    private DocSurveyMapper docSurveyMapper;

    @Autowired
    private UserService userService;

    @Override
    public CommonResult<List<String>> listProjectName() {
        CommonResult<List<String>>  rs = new CommonResult<>();
        try{
            QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
            projectQueryWrapper.select("project_name").groupBy("project_name");
            List<String> projectNameList = mapper.selectMaps(projectQueryWrapper).stream().map(map -> map.get("project_name").toString()).collect(Collectors.toList());
            rs.setCode(0);
            rs.setMsg("查询成功");
            rs.setData(projectNameList);
            return rs;
        }catch (Exception e){
            rs.setCode(-1);
            rs.setMsg("发生错误"+e.getMessage());
            return rs;
        }
    }

    @Override
    public Project getProjectInfo(Integer projectId){
        Project project = mapper.selectById(projectId);
        return project;
    }
    @Override
    public CommonResult<List<Project>> search(String projectName, Integer state, Date startTime, Date endTime, Integer page, Integer size) {
        CommonResult<List<Project>> rs = new CommonResult<>();
        try {
            Page<Project> pg = new Page<>(page,size);// 创建分页对象
            QueryWrapper<Project> queryWrapper = new QueryWrapper<>();

            if (projectName != null && !projectName.isEmpty()) {
                queryWrapper.like("project_name", projectName);  // 模糊匹配项目名称
            }

            if (state != null) {
                queryWrapper.eq("state", state); // 按状态过滤
            }

            if (startTime != null && endTime != null) {
                if (startTime.after(endTime)) {
                    throw new IllegalArgumentException("开始时间不能晚于结束时间");
                }
                queryWrapper.ge("begin_date", startTime); // 'begin_date' >= startTime
                queryWrapper.le("end_date", endTime); // 'end_date' <= endTime
            } else if (startTime != null) {
                queryWrapper.ge("begin_date", startTime); // 'begin_date' >= startTime
            } else if (endTime != null) {
                queryWrapper.le("end_date", endTime); // 'end_date' <= endTime
            }

            // 获取分页数据
            mapper.selectPage(pg, queryWrapper);
            List<Project> list = pg.getRecords();
            long count = pg.getTotal();

            rs.setCode(0);
            rs.setMsg("查询成功");
            rs.setCount((int) count);
            rs.setData(list);
            return rs;
        } catch (IllegalArgumentException e) {
            rs.setCode(-1);
            rs.setMsg("参数错误: " + e.getMessage());
            return rs;
        } catch (Exception e) {
            rs.setCode(-1);
            rs.setMsg("发生错误: " + e.getMessage());
            return rs;
        }
    }



    @Override
    public CommonResult save(Project project){
        CommonResult<Project> rs = new CommonResult<>();
        try{
            if(project.getId() == null || project.getId() == 0){
                // New Project
                project.setCreateDate(new java.util.Date());
                //判断项目人数是否>0
                if(project.getNum()<=0){
                    rs.setCode(-1);
                    rs.setMsg("项目人数必须大于0");
                    return rs;
                }
                mapper.insert(project);
                rs.setCode(0);
                rs.setMsg("创建成功");
                rs.setData(project);
            } else {
                // Existing Project
                //判断项目人数是否>0
                if(project.getNum()<=0){
                    rs.setCode(-1);
                    rs.setMsg("项目人数必须大于0");
                    return rs;
                }
                int rows = mapper.updateById(project);
                if(rows > 0){
                    rs.setCode(0);
                    rs.setMsg("更新成功");
                    rs.setData(project);
                } else {
                    rs.setCode(-1);
                    rs.setMsg("项目不存在或更新失败");
                }
            }
            return rs;
        } catch (Exception e){
            rs.setCode(-1);
            rs.setMsg("发生错误: " + e.getMessage());
            return rs;
        }
    }

    @Override
    public CommonResult<List<Project>> list() {
        CommonResult rs = new CommonResult();
        rs.setData(mapper.selectList(null));
        rs.setCode(0);
        return rs;
    }




    @Override
    public CommonResult delete(Integer id){
        CommonResult rs = new CommonResult();
        try{
            int k = mapper.deleteById(id);
            if(k>0){
                rs.setCode(0);
                rs.setMsg("删除成功");
            }else{
                rs.setCode(-1);
                rs.setMsg("删除失败");
            }
            return rs;
        }catch (Exception exception){
            rs.setCode(-1);
            rs.setMsg("发生错误：" +exception.getMessage());
            return rs;
        }
    }



    @Override
    public List<Project> getAllProjects(){
        return mapper.selectList(null); // Fetches all projects
    }

    @Override
    public DocReportVO getdocReportInfo(Integer projectid, HttpSession session) {
        DocReportVO docReportVO = new DocReportVO();

        //设置项名称
        Project project = mapper.selectById(projectid);
        if(project != null){
            docReportVO.setProjectName(project.getProjectName());
        }

        //设置当前用户
        User currentUser = userService.getLoginUser(session);
        docReportVO.setCurrentUser(currentUser);

        //设置审批人
        DocReport docReport = docReportMapper.selectOne(
                new QueryWrapper<DocReport>()
                        .eq("project_id", projectid)  // 根据 project_id 筛选
                        .orderByDesc("submit_date")   // 按 create_time 降序排序
                        .last("LIMIT 1")              // 只获取一条最新记录
        );

        if(docReport != null){
            BeanUtils.copyProperties(docReport, docReportVO);
            Integer confirmId = docReport.getConfirmId();
            if(confirmId != null){
                User user = userMapper.selectById(confirmId);
                docReportVO.setConfirmUser(user);
            }else{
                User user = new User();
                user.setId(null);
                user.setUserName(null);
                user.setRealName(null);
                user.setUserPwd(null);
                user.setRole(null);
                user.setTel(null);
                user.setEmail(null);
                docReportVO.setConfirmUser(user);
            }
        }else{
            User user = new User();
            user.setId(null);
            user.setUserName(null);
            user.setRealName(null);
            user.setUserPwd(null);
            user.setRole(null);
            user.setTel(null);
            user.setEmail(null);
            docReportVO.setConfirmUser(user);
        }
        return docReportVO;
    }

    @Override
    public DocSchemeVO getdocSchemeInfo(Integer projectId, HttpSession session) {
        DocSchemeVO docSchemeVO = new DocSchemeVO();

        //设置项目名称
        Project project = mapper.selectById(projectId);
        if(project != null){
            docSchemeVO.setProjectName(project.getProjectName());
        }

        //设置审批人
        DocScheme docScheme = docSchemeMapper.selectOne(
                new QueryWrapper<DocScheme>()
                        .eq("project_id", projectId)  // 根据 project_id 筛选
                        .orderByDesc("submit_date")   // 按 submit_date 降序排序
                        .last("LIMIT 1")              // 只获取一条最新记录
        );

        //设置当前用户
        User currentUser = userService.getLoginUser(session);
        docSchemeVO.setCurrentUser(currentUser);

        if(docScheme != null){
            BeanUtils.copyProperties(docScheme, docSchemeVO);
            Integer confirmId = docScheme.getConfirmId();
            if(confirmId != null){
                User user = userMapper.selectById(confirmId);
                docSchemeVO.setConfirmUser(user);
            }else{
                User user = new User();
                user.setId(null);
                user.setUserName(null);
                user.setRealName(null);
                user.setUserPwd(null);
                user.setRole(null);
                user.setTel(null);
                user.setEmail(null);
                docSchemeVO.setConfirmUser(user);
            }
        }else{
            User user = new User();
            user.setId(null);
            user.setUserName(null);
            user.setRealName(null);
            user.setUserPwd(null);
            user.setRole(null);
            user.setTel(null);
            user.setEmail(null);
            docSchemeVO.setConfirmUser(user);
        }
        return docSchemeVO;
    }

    @Override
    public DocSurveyVO getdocsurveyInfo(Integer projectId, HttpSession session) {
        DocSurveyVO docSurveyVO = new DocSurveyVO();

        Project project = mapper.selectById(projectId);
        if(project != null){
            docSurveyVO.setProjectName(project.getProjectName());
        }

        DocSurvey docSurvey = docSurveyMapper.selectOne(
                new QueryWrapper<DocSurvey>()
                        .eq("project_id", projectId)  // 根据 project_id 筛选
                        .orderByDesc("submit_date")   // 按 submit_date 降序排序
                        .last("LIMIT 1")

        );

        User currentUser = userService.getLoginUser(session);
        docSurveyVO.setCurrentUser(currentUser);

        if(docSurvey != null){
            BeanUtils.copyProperties(docSurvey, docSurveyVO);
            Integer confirmId = docSurvey.getConfirmId();
            if (confirmId != null){
                User user = userMapper.selectById(confirmId);
                docSurveyVO.setConfirmUser(user);
            }else{
                User user = new User();
                user.setId(null);
                user.setUserName(null);
                user.setRealName(null);
                user.setUserPwd(null);
                user.setRole(null);
                user.setTel(null);
                user.setEmail(null);
                docSurveyVO.setConfirmUser(user);
            }
        }else{
            User user = new User();
            user.setId(null);
            user.setUserName(null);
            user.setRealName(null);
            user.setUserPwd(null);
            user.setRole(null);
            user.setTel(null);
            user.setEmail(null);
            docSurveyVO.setConfirmUser(user);
        }
        return docSurveyVO;
    }


    @Override
    public CommonResult<Boolean> saveDoc_Survey(DocSurveyVO docSurveyVO, HttpSession session) {
        CommonResult<Boolean> result = new CommonResult<>();
        try{
            //插入诊断报告记录
            DocSurvey docSurvey = new DocSurvey();
            BeanUtils.copyProperties(docSurveyVO, docSurvey);

            String projectName = docSurveyVO.getProjectName();
            QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
            projectQueryWrapper.eq("project_name", projectName);
            Project project = projectMapper.selectOne(projectQueryWrapper);
            if (project != null){
                docSurvey.setProjectId(Long.valueOf(project.getId()));
            }else{
                docSurvey.setProjectId(null);
            }

            int i = 0;
            User loginUser = userService.getLoginUser(session);

            //管理员审核
            if("管理员".equals(loginUser.getRole())){
                Date date = new Date();
                //审批时间
                docSurvey.setConfirmDate(date);
                //审批人
                docSurvey.setConfirmId(loginUser.getId());
                i = docSurveyMapper.updateById(docSurvey);

            }
            //第一次上报或者被打回
            else if("二级学院用户".equals(loginUser.getRole())){
                Date date = new Date();
                docSurvey.setSubmitDate(date);
                docSurvey.setUserId(loginUser.getId());
                docSurvey.setState(docSurveyVO.getState());
                docSurvey.setVersion(date.getTime());
                docSurvey.setConfirmId(null);
                docSurvey.setConfirmDate(null);
                //打回之后上报
                if(docSurveyVO.getId() != null){
                    docSurvey.setId(0L);
                    docSurvey.setAdvice(null);
                }
                i = docSurveyMapper.insert(docSurvey);
            }

            if(i > 0){
                result.setCode(0);
                result.setMsg("保存成功");
                result.setData(true);
                return result;
            }else{
                result.setCode(-1);
                result.setMsg("保存失败");
                result.setData(false);
                return result;
            }
        }catch (Exception e){
            result.setCode(-1);
            result.setMsg("发生错误："+e.getMessage());
            return result;
        }
    }

    @Override
    public CommonResult<Boolean> saveDoc_Report(DocReportVO docReportVO, HttpSession session) {
        CommonResult<Boolean> rs = new CommonResult<>();
        try{
            DocReport docReport = new DocReport();
            BeanUtils.copyProperties(docReportVO, docReport);

            String projectName = docReportVO.getProjectName();
            QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
            projectQueryWrapper.eq("project_name", projectName);
            Project project = projectMapper.selectOne(projectQueryWrapper);
            if (project != null){
                docReport.setProjectId(project.getId());
            }else{
                docReport.setProjectId(null);
            }

            int i = 0;
            User loginUser = userService.getLoginUser(session);

            //管理员审核
            if("管理员".equals(loginUser.getRole())){
                Date date = new Date();
                //审批时间
                docReport.setConfirmDate(date);
                //审批人
                docReport.setConfirmId(loginUser.getId());
                i = docReportMapper.updateById(docReport);
            }
            //第一次上报或者被打回
            else if("二级学院用户".equals(loginUser.getRole())){
                Date date = new Date();
                docReport.setSubmitDate(date);
                docReport.setUserId(loginUser.getId());
                docReport.setState(docReportVO.getState());
                docReport.setVersion(date.getTime());
                docReport.setConfirmId(null);
                docReport.setConfirmDate(null);
                //打回之后上报
                if(docReportVO.getId() != null){
                    docReport.setId(0);
                    docReport.setAdvice(null);
                }
                i = docReportMapper.insert(docReport);
            }

            if(i > 0){
                rs.setCode(0);
                rs.setMsg("保存成功");
                rs.setData(true);
                return rs;
            }else{
                rs.setCode(-1);
                rs.setMsg("保存失败");
                rs.setData(false);
                return rs;
            }
        }catch (Exception e){
            rs.setCode(-1);
            rs.setMsg("发生错误："+e.getMessage());
            return rs;
        }
    }

    @Override
    public CommonResult<Boolean> saveDoc_Scheme(DocSchemeVO docSchemeVO, HttpSession session) {
        CommonResult<Boolean> rs = new CommonResult<>();
        try{
            DocScheme docScheme = new DocScheme();
            BeanUtils.copyProperties(docSchemeVO, docScheme);

            String projectName = docSchemeVO.getProjectName();
            QueryWrapper<Project> projectQueryWrapper = new QueryWrapper<>();
            projectQueryWrapper.eq("project_name", projectName);
            Project project = projectMapper.selectOne(projectQueryWrapper);
            if (project != null){
                docScheme.setProjectId(Long.valueOf(project.getId()));
            }else{
                docScheme.setProjectId(null);
            }

            int i = 0;
            User loginUser = userService.getLoginUser(session);

            //管理员审核
            if("管理员".equals(loginUser.getRole())){
                Date date = new Date();
                //审批时间
                docScheme.setConfirmDate(date);
                //审批人
                docScheme.setConfirmId(loginUser.getId());
                i = docSchemeMapper.updateById(docScheme);

            }
            //第一次上报或者被打回
            else if("二级学院用户".equals(loginUser.getRole())){
                Date date = new Date();
                docScheme.setSubmitDate(date);
                docScheme.setUserId(loginUser.getId());
                docScheme.setState(0);
                docScheme.setVersion(date.getTime());
                docScheme.setConfirmId(null);
                docScheme.setConfirmDate(null);
                //打回之后上报
                if(docSchemeVO.getId() != null){
                    docScheme.setId(0L);
                    docScheme.setAdvice(null);
                }
                i = docSchemeMapper.insert(docScheme);
            }

            if(i > 0){
                rs.setCode(0);
                rs.setMsg("保存成功");
                rs.setData(true);
                return rs;
            }else{
                rs.setCode(-1);
                rs.setMsg("保存失败");
                rs.setData(false);
                return rs;
            }

        }catch (Exception e){
            rs.setCode(-1);
            rs.setMsg("发生错误：" + e.getMessage());
            return rs;
        }
    }


    @Override
    public Map<String, Integer> getProjectStatusStatistics() {
        List<Map<String, Object>> results = projectMapper.countProjectStatus();
        Map<String, Integer> statistics = new HashMap<>();
        for (Map<String, Object> result : results) {
            statistics.put(result.get("state").toString(), Integer.parseInt(result.get("count").toString()));
        }
        return statistics;
    }
    @Override
    public List<DefaultVersionInfoVO> getVersionInfoDefault(Integer projectId, HttpSession session) {
        //默认展示调查问卷的版本信息
        QueryWrapper<DocSurvey> wrapper = new QueryWrapper<>();
        wrapper.eq("project_id", projectId);
        List<DocSurvey> docSurveys = docSurveyMapper.selectList(wrapper);
        DefaultVersionInfoVO defaultVersionInfoVO = new DefaultVersionInfoVO();

        ArrayList<DefaultVersionInfoVO> defaultVersionInfoVOS = new ArrayList<>();
        for(DocSurvey docSurvey : docSurveys){
            defaultVersionInfoVO = docServerToDefaultVersionInfoVO(docSurvey);
            defaultVersionInfoVO.setProjectId(projectId);
            defaultVersionInfoVOS.add(defaultVersionInfoVO);

        }

        return defaultVersionInfoVOS;
    }

    @Override
    public List<SchemaVersionInfoVO> getSchameVersionInfo(Integer projectId) {
        QueryWrapper<DocScheme> wrapper = new QueryWrapper<>();
        wrapper.eq("project_id", projectId);
        List<DocScheme> docSchemes = docSchemeMapper.selectList(wrapper);
        SchemaVersionInfoVO schemaVersionInfoVO = new SchemaVersionInfoVO();

        ArrayList<SchemaVersionInfoVO> schemaVersionInfoVOS = new ArrayList<>();
        for(DocScheme docScheme : docSchemes){
            schemaVersionInfoVO = docSchemaToDocShemaVersionInfoVO(docScheme);
            schemaVersionInfoVO.setProjectId(projectId);
            schemaVersionInfoVOS.add(schemaVersionInfoVO);

        }
        return schemaVersionInfoVOS;
    }

    @Override
    public List<ReportVersionInfoVO> getReportVersionInfo(Integer projectId) {
        QueryWrapper<DocReport> wrapper = new QueryWrapper<>();
        wrapper.eq("project_id", projectId);
        List<DocReport> docReports = docReportMapper.selectList(wrapper);
        ReportVersionInfoVO reportVersionInfoVO = new ReportVersionInfoVO();

        ArrayList<ReportVersionInfoVO> reportVersionInfoVOS = new ArrayList<>();
        for(DocReport docReport : docReports){
            reportVersionInfoVO = docReportToDocReportVersionInfoVO(docReport);
            reportVersionInfoVO.setProjectId(projectId);
            reportVersionInfoVOS.add(reportVersionInfoVO);

        }
        return reportVersionInfoVOS;
    }

    private ReportVersionInfoVO docReportToDocReportVersionInfoVO(DocReport docReport) {
        ReportVersionInfoVO reportVersionInfoVO = new ReportVersionInfoVO();
        Integer userId = docReport.getUserId();
        User user = userMapper.selectById(userId);
        reportVersionInfoVO.setSubUser(user.getUserName());
        reportVersionInfoVO.setSubDate(DateUtil.format(docReport.getSubmitDate(), "yyyy-MM-dd"));
        reportVersionInfoVO.setVersion(String.valueOf(docReport.getVersion()));
        Integer projectId = docReport.getProjectId();
        Project project = projectMapper.selectById(projectId);
        reportVersionInfoVO.setProjectName(project.getProjectName());
        return reportVersionInfoVO;
    }

    private SchemaVersionInfoVO docSchemaToDocShemaVersionInfoVO(DocScheme docScheme) {
        SchemaVersionInfoVO schemaVersionInfoVO = new SchemaVersionInfoVO();
        Integer userId = docScheme.getUserId();
        User user = userMapper.selectById(userId);
        schemaVersionInfoVO.setSubUser(user.getUserName());
        schemaVersionInfoVO.setSubDate(DateUtil.format(docScheme.getSubmitDate(), "yyyy-MM-dd"));
        schemaVersionInfoVO.setVersion(String.valueOf(docScheme.getVersion()));
        Long projectId = docScheme.getProjectId();
        Project project = projectMapper.selectById(projectId);
        schemaVersionInfoVO.setProjectName(project.getProjectName());
        return schemaVersionInfoVO;
    }

    private DefaultVersionInfoVO docServerToDefaultVersionInfoVO(DocSurvey docSurvey){
        DefaultVersionInfoVO defaultVersionInfoVO = new DefaultVersionInfoVO();
        Integer userId = docSurvey.getUserId();
        User user = userMapper.selectById(userId);
        defaultVersionInfoVO.setSubUser(user.getUserName());
        defaultVersionInfoVO.setSubDate(DateUtil.format(docSurvey.getSubmitDate(), "yyyy-MM-dd"));
        defaultVersionInfoVO.setVersion(String.valueOf(docSurvey.getVersion()));
        Long projectId = docSurvey.getProjectId();
        Project project = projectMapper.selectById(projectId);
        defaultVersionInfoVO.setProjectName(project.getProjectName());
        return defaultVersionInfoVO;
    }

}
